const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const User = require('./User');

class QuestionSet extends Model {}

QuestionSet.init(
  {
    id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      allowNull: false,
      comment: '题库ID'
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '题库名称'
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '题库描述'
    },
    user_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '创建者ID',
      references: {
        model: User,
        key: 'user_id'
      }
    },
    question_count: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '题目数量'
    },
    create_time: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    },
    update_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '更新时间'
    },
  },
  {
    sequelize,
    modelName: 'QuestionSet',
    tableName: 'question_set',
    timestamps: false,
    indexes: [
      {
        fields: ['user_id']
      }
    ]
  }
);

// 建立与User的关联关系
QuestionSet.belongsTo(User, {
  foreignKey: 'user_id',
  targetKey: 'user_id',
  as: 'creator'
});

// 在User模型中添加关联，会在User模型加载后生效
setTimeout(() => {
  if (User.hasMany) {
    User.hasMany(QuestionSet, {
      foreignKey: 'user_id',
      sourceKey: 'user_id',
      as: 'questionSets'
    });
  }
}, 0);

module.exports = QuestionSet; 